import Router from "@koa/router";

import moment from "moment";
import axios from "axios";
import sha1 from "sha1";

const router = new Router();

const token = "YNKC1234";
const appid = "wx095e9d0423d44dad";
const appsecret='6c68ce2de872a175e41f354dbd7ea12e'

async function GetSign(timestamp, nonce) {
  const str = [token, timestamp, nonce].sort().join("");
  return sha1(str);
}
async function _get(url) {
  try {
      const response = await axios.get(url);
      return response.data;
  } catch (error) {
      throw new Error(`请求失败: ${error.message}`);
  }
}
async function GetOpenID(code) {
  const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`;
  try {
      const res = await _get(url);
      console.info("获取OpenID成功", `请求URL==>${url}  响应==>${JSON.stringify(res)}`);
      return { code: 1, data: res };
  } catch (error) {
      console.error("用Code获取OpneID出错", `请求URL==>${url}`, error.message);
      return { code: 0, msg: "用Code获取OpneID出错:" + error.message };
  }
}

router.all("/auth", async (ctx) => {
//授权消息验证
const { signature, timestamp, nonce } = ctx.query;
//字典排序
let result = await GetSign( timestamp, nonce);
if (result === signature) {
  ctx.body = ctx.query.echostr;
} else {
  ctx.body = { code: -1, msg: "fail" };
}
});

router.get("/oauth/GetWeChatBase", async (ctx) => {
  console.log("进入获取OpenID", appid);
  let { code, skipUrl } = ctx.query;
  if (!code) {
    //无code，说明是需要openid的对象
    let selfUrl = `https://shop.ynkczx.cn/oauth/GetWeChatBase?skipUrl=${skipUrl}`;
    console.log("selfUrl", selfUrl);
    let wechatUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${selfUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    ctx.status = 301;
    ctx.redirect(wechatUrl);
    return;
  } else {
    console.info("微信跳转 获取openid", ctx.query);
    skipUrl = Buffer.from(skipUrl, "base64").toString();
    let result = await GetOpenID( ctx.query.code);
    console.log("获取openid", result);
    if (result && result.data && result.data.openid) {
      //let url = Buffer.from(skipUrl, 'base64').toString();
      let finalUrl = skipUrl + `?openid=${result.data.openid}&appid=${appid}`;
      ctx.status = 301;
      ctx.redirect(finalUrl);
      console.log("获取openid重定向地址", finalUrl);
      return;
    }
    ctx.status = 301;
    ctx.redirect(skipUrl);
  }
});


export { router };
